package com.spring.bean;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.jdbc.core.RowMapper;

import com.spring.annotation.entity.NotPersistent;
import com.spring.annotation.search.SearchableComponent;
import com.spring.utils.StringUtils;

public class MyRowMapper<T> implements RowMapper {

	private Class<T> cls;
 	
	public MyRowMapper(Class<T> cls) {
		this.cls = cls;
	}
	
	@Override
	public Object mapRow(ResultSet rs, int num) throws SQLException {
		T t = null;
		try {
			// 获取对象中的字段
			Field[] fields = cls.getDeclaredFields();
			// 实例化
			t = cls.newInstance();
			for(Field f : fields){
				if(f.isAnnotationPresent(NotPersistent.class)){
					continue;
				}
				String fieldName = f.getName();
				if(StringUtils.isBlank(fieldName)){
					continue;
				}
				Object o = null;
				try {
					o = rs.getObject(fieldName);
				} catch (SQLException e) {
					continue;
				}
				if(o == null){
					continue;
				}
				BeanUtils.setProperty(t, fieldName, o);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}

}
